﻿/*
 * Created by SharpDevelop.
 * User: DELL
 * Date: 07/28/2012
 * Time: 20:29
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.Practices.Prism.Regions;

namespace IntoNails.Infrastructure.Views.Behaviors
{
    [Export(typeof(AutoPopulateExportedRegionBehavior))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
	public class AutoPopulateExportedRegionBehavior : RegionBehavior, IPartImportsSatisfiedNotification
	{
		protected override void OnAttach()
        {
            AddRegisteredViews();
        }

        public void OnImportsSatisfied()
        {
            AddRegisteredViews();
        }

        /// <summary>
        /// Adds all registered views to the region in the shell.
        /// </summary>
        private void AddRegisteredViews()
        {
            if (null == this.Region)
            {
                return;
            }

            var views = from v in this.RegisteredViews
                        where v.Metadata.RegionName == this.Region.Name
                        select v.Value
                        into view
                        where !this.Region.Views.Contains(view)
                        select view;

            foreach (var viewEntry in views)
            {
                this.Region.Add(viewEntry);
            }
        }

	    [ImportMany(AllowRecomposition = true)]
        public Lazy<object, IViewRegionRegistration>[] RegisteredViews { get; set; }
	}
}
